<script setup lang="ts">
import { ref, watch, nextTick, onMounted, onUnmounted, computed } from "vue";

import { useRouter } from 'vue-router'

const router = useRouter()

// 健康提示数据
const healthTip = ref("您的血压指标近期有波动，建议及时进行复查并...");

// 药物小常识数据
const medicineInfo = ref({
  title: "阿司匹林服用小贴士：",
  content:
    "阿司匹林是一种常见的解热镇痛药，但它的使用方法和注意事项却常常被人们忽视。",
});

// 示例问题
const exampleQuestions = ref([
  "肚子疼,怎么办？",
  "嗓子疼，需要注意什么？",
]);

// 控制功能菜单显示
const showFunctionMenu = ref(false);

// 历史记录相关状态
const showHistoryModal = ref(false);
const isHistoryClosing = ref(false);
const historySearchKeyword = ref('');
const searchHistory = ref<Array<{
  id: string,
  type: 'text' | 'image' | 'file',
  query: string,
  result: string,
  timestamp: Date
}>>([]);

// 功能菜单选项
const functionMenuItems = ref([
  { icon: "📷", text: "照片", action: "photo" },
  { icon: "📸", text: "拍照", action: "camera" },
  { icon: "📁", text: "文件分析", action: "fileAnalysis" },
]);

// 后端API配置
const BACKEND_API_URL = 'http://localhost:3000'; // 根据实际后端地址调整
   
// 照片分析相关状态
const isAnalyzing = ref(false);
const fileInputRef = ref<HTMLInputElement | null>(null);



// AI对话相关状态
const userInput = ref('');
const isSending = ref(false);
const chatHistory = ref<Array<{
  role: 'user' | 'assistant', 
  content: string, 
  timestamp: Date,
  imageUrl?: string, // 添加可选的图片URL字段
  videoUrl?: string  // 添加可选的视频URL字段
}>>([]);
const currentAnswer = ref('');

// 选中图片的状态管理
const selectedImage = ref<File | null>(null);
const selectedImagePreview = ref<string>('');

// 选中视频的状态管理
const selectedVideo = ref<File | null>(null);
const selectedVideoPreview = ref<string>('');

// 文件分析相关状态
const selectedFile = ref<File | null>(null);
const selectedFilePreview = ref<string>('');
const analysisType = ref<'general' | 'medical' | 'technical'>('general');
const fileInputForAnalysisRef = ref<HTMLInputElement | null>(null);

// 拍照功能相关状态
const isCameraOpen = ref(false);
const videoRef = ref<HTMLVideoElement | null>(null);
const canvasRef = ref<HTMLCanvasElement | null>(null);
const cameraStream = ref<MediaStream | null>(null);

// 视频录制相关状态
const isVideoRecording = ref(false);
const mediaRecorder = ref<MediaRecorder | null>(null);
const recordedChunks = ref<Blob[]>([]);
const recordingTime = ref(0);
const recordingTimer = ref<number | null>(null);

// 将图片转换为base64
const convertImageToBase64 = (file: File): Promise<string> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => {
      const result = reader.result as string;
      resolve(result);
    };
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
};

// 调用后端API进行图片分析
const analyzeImageWithBackend = async (file: File): Promise<string> => {
  try {
    console.log('开始调用OCR图片分析API...');
    
    const formData = new FormData();
    formData.append('image', file);
    
    const response = await fetch(`${BACKEND_API_URL}/AI/api/analyze-image-ocr`, {
      method: 'POST',
      body: formData
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.error || `请求失败: ${response.status}`);
    }

    const data = await response.json();

    if (data.success && data.data) {
      return data.data.analysis;
    } else {
      throw new Error(data.error || '响应格式异常');
    }
  } catch (error) {
    console.error('OCR图片分析API调用错误:', error);
    
    if (error instanceof TypeError && error.message.includes('fetch')) {
      throw new Error('网络连接失败，请检查网络连接');
    } else if (error instanceof Error) {
      throw new Error(`OCR分析失败: ${error.message}`);
    } else {
      throw new Error('OCR分析失败，未知错误');
    }
  }
};

// 图片+文字组合分析函数
const analyzeImageWithText = async (file: File, userMessage: string): Promise<string> => {
  try {
    console.log('开始调用图片+文字组合分析API...');
    
    const formData = new FormData();
    formData.append('image', file);
    formData.append('message', userMessage || '请分析这张图片');
    formData.append('analysisType', 'comprehensive'); // 综合分析类型
    
    const response = await fetch(`${BACKEND_API_URL}/AI/api/analyze-image-comprehensive`, {
      method: 'POST',
      body: formData
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.error || `请求失败: ${response.status}`);
    }

    const data = await response.json();

    if (data.success && data.data) {
      return data.data.analysis;
    } else {
      throw new Error(data.error || '响应格式异常');
    }
  } catch (error) {
    console.error('图片+文字组合分析API调用错误:', error);
    
    if (error instanceof TypeError && error.message.includes('fetch')) {
      throw new Error('网络连接失败，请检查网络连接');
    } else if (error instanceof Error) {
      throw new Error(`组合分析失败: ${error.message}`);
    } else {
      throw new Error('组合分析失败，未知错误');
    }
  }
};





// 调用后端API进行文本对话
const chatWithBackend = async (message: string, chatHistory: Array<{role: string, content: string}>): Promise<string> => {
  try {
    console.log('开始调用后端对话API...');
    
    const response = await fetch(`${BACKEND_API_URL}/AI/api/chat`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        message: message,
        chatHistory: chatHistory
      })
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.error || `请求失败: ${response.status}`);
    }

    const data = await response.json();

    if (data.success && data.data) {
      return data.data.content;
    } else {
      throw new Error(data.error || '响应格式异常');
    }
  } catch (error) {
    console.error('后端API调用错误:', error);
    
    if (error instanceof TypeError && error.message.includes('fetch')) {
      throw new Error('网络连接失败，请检查网络连接');
    } else if (error instanceof Error) {
      throw new Error(`对话失败: ${error.message}`);
    } else {
      throw new Error('对话失败，未知错误');
    }
  }
};

// 文件+文字分析函数
const analyzeFileWithText = async (file: File, message: string, type: string = 'general'): Promise<string> => {
  try {
    console.log('开始调用文件+文字分析API...');
    
    const formData = new FormData();
    formData.append('file', file);
    formData.append('message', message);
    formData.append('analysisType', type);
    
    const response = await fetch(`${BACKEND_API_URL}/AI/api/analyze-file-with-text`, {
      method: 'POST',
      body: formData
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.error || `请求失败: ${response.status}`);
    }

    const data = await response.json();

    if (data.success && data.data) {
      return data.data.analysis;
    } else {
      throw new Error(data.error || '响应格式异常');
    }
  } catch (error) {
    console.error('文件+文字分析API调用错误:', error);
    
    if (error instanceof TypeError && error.message.includes('fetch')) {
      throw new Error('网络连接失败，请检查网络连接');
    } else if (error instanceof Error) {
      throw new Error(`分析失败: ${error.message}`);
    } else {
      throw new Error('分析失败，未知错误');
    }
  }
};

// 存储所有活跃的定时器
const activeTimers = ref<Set<number>>(new Set());

// 打字机效果函数
const typewriterEffect = (text: string, targetIndex: number, speed: number = 50) => {
  let currentIndex = 0;
  const timer = setInterval(() => {
    if (currentIndex <= text.length) {
      chatHistory.value[targetIndex].content = text.substring(0, currentIndex);
      currentIndex++;
      
      nextTick(() => {
        scrollToBottom();
      });
    } else {
      clearInterval(timer);
      activeTimers.value.delete(timer);
    }
  }, speed);
  
  // 将定时器添加到活跃定时器集合中
  activeTimers.value.add(timer);
  
  return timer;
};

// 处理发送消息
const handleSendMessage = async () => {
  // 检查是否有文字输入、选中的图片或文件
  if ((!userInput.value.trim() && !selectedImage.value && !selectedFile.value) || isSending.value) {
    return;
  }

  const message = userInput.value.trim();
  const imageFile = selectedImage.value;
  const analysisFile = selectedFile.value;
  
  try {
    isSending.value = true;
    
    // 立即清空输入框和选中的文件
    userInput.value = '';
    const tempImageFile = imageFile;
    const tempImagePreview = selectedImagePreview.value;
    const tempAnalysisFile = analysisFile;
    const tempFilePreview = selectedFilePreview.value;
    
    selectedImage.value = null;
    selectedImagePreview.value = '';
    selectedFile.value = null;
    selectedFilePreview.value = '';
    
    // 处理文件分析
        if (tempAnalysisFile) {
          // 添加用户上传的文件到聊天历史
          chatHistory.value.push({
            role: 'user',
            content: message ? `📁 ${message}` : `📁 上传了文件：${tempAnalysisFile.name}`,
            timestamp: new Date(),
            imageUrl: tempFilePreview // 如果是图片文件，显示预览
          });
          
          // 添加分析中的提示消息
          chatHistory.value.push({
            role: 'assistant',
            content: '🔍 正在分析您上传的文件，请稍候...',
            timestamp: new Date()
          });
          
          // 滚动到底部
          nextTick(() => {
            scrollToBottom();
          });
          
          // 调用文件+文字分析接口
          const result = await analyzeFileWithText(tempAnalysisFile, message || '请分析这个文件', analysisType.value);
          
          // 移除"分析中"的消息
          chatHistory.value.pop();
          
          // 添加分析结果到聊天历史（使用打字机效果）
          const resultIndex = chatHistory.value.length;
          chatHistory.value.push({
            role: 'assistant',
            content: '',
            timestamp: new Date()
          });
          
          // 启动打字机效果
            typewriterEffect(result, resultIndex);
            
            // 标记消息完成
            setTimeout(() => {
              if (chatHistory.value[resultIndex]) {
                chatHistory.value[resultIndex].content = result;
                nextTick(() => {
                  const messageElement = document.querySelector(`.message:nth-child(${resultIndex + 1}) .message-text`);
                  if (messageElement) {
                    messageElement.classList.add('message-complete');
                  }
                });
              }
            }, result.length * 50 + 100);
          
          // 标记消息完成
          setTimeout(() => {
            if (chatHistory.value[resultIndex]) {
              chatHistory.value[resultIndex].content = result;
              nextTick(() => {
                const messageElement = document.querySelector(`.message:nth-child(${resultIndex + 1}) .message-text`);
                if (messageElement) {
                  messageElement.classList.add('message-complete');
                }
              });
            }
          }, result.length * 50 + 100);
          
          // 添加到搜索历史
          addSearchHistory('file', message || `文件：${tempAnalysisFile.name}`, result);
          
        } else if (tempImageFile) {
          // 添加用户上传的图片到聊天历史
          chatHistory.value.push({
            role: 'user',
            content: message ? `📷 ${message}` : `📷 上传了图片：${tempImageFile.name}`,
            timestamp: new Date(),
            imageUrl: tempImagePreview
          });
          
          // 添加分析中的提示消息
          chatHistory.value.push({
            role: 'assistant',
            content: '🔍 正在进行图片内容识别和智能分析，请稍候...',
            timestamp: new Date()
          });
          
          // 滚动到底部
          nextTick(() => {
            scrollToBottom();
          });
          
          // 根据是否有文字描述选择不同的分析方式
          let result;
          if (message && message.trim()) {
            // 有文字描述：使用综合分析（OCR + 文字描述 + AI分析）
            result = await analyzeImageWithText(tempImageFile, message);
          } else {
            // 无文字描述：仅使用OCR分析
            result = await analyzeImageWithBackend(tempImageFile);
          }
          
          const fullResult = `📷 图片分析结果：\n\n${result}`;
          
          // 移除"分析中"的消息
          chatHistory.value.pop();
          
          // 添加分析结果到聊天历史（使用打字机效果）
          const resultIndex = chatHistory.value.length;
          chatHistory.value.push({
            role: 'assistant',
            content: '',
            timestamp: new Date()
          });
          
          // 启动打字机效果
          typewriterEffect(fullResult, resultIndex);
          
          // 标记消息完成
          setTimeout(() => {
            if (chatHistory.value[resultIndex]) {
              chatHistory.value[resultIndex].content = fullResult;
              nextTick(() => {
                const messageElement = document.querySelector(`.message:nth-child(${resultIndex + 1}) .message-text`);
                if (messageElement) {
                  messageElement.classList.add('message-complete');
                }
              });
            }
          }, fullResult.length * 50 + 100);
          
          // 添加到搜索历史
          addSearchHistory('image', message || `图片：${tempImageFile.name}`, result);
          
        } else if (message) {
      // 只有文字消息的处理逻辑
      // 添加用户消息到历史记录
      chatHistory.value.push({
        role: 'user',
        content: message,
        timestamp: new Date()
      });
      
      // 准备发送给后端的消息历史
      const apiChatHistory = chatHistory.value.slice(0, -1).map(msg => ({
        role: msg.role,
        content: msg.content
      }));
      
      // 调用后端API
      const aiResponse = await chatWithBackend(message, apiChatHistory);
      
      // 添加AI回复到历史记录（使用打字机效果）
      const responseIndex = chatHistory.value.length;
      chatHistory.value.push({
        role: 'assistant',
        content: '',
        timestamp: new Date()
      });
      
      // 启动打字机效果
      typewriterEffect(aiResponse, responseIndex);
      
      // 标记消息完成
      setTimeout(() => {
        if (chatHistory.value[responseIndex]) {
          chatHistory.value[responseIndex].content = aiResponse;
          nextTick(() => {
            const messageElement = document.querySelector(`.message:nth-child(${responseIndex + 1}) .message-text`);
            if (messageElement) {
              messageElement.classList.add('message-complete');
            }
          });
        }
      }, aiResponse.length * 50 + 100);
      
      // 设置当前回答
      currentAnswer.value = aiResponse;
      
      // 添加到搜索历史
      addSearchHistory('text', message, aiResponse);
    }
    
    // 滚动到底部显示结果
    nextTick(() => {
      scrollToBottom();
    });
    
  } catch (error) {
    console.error('发送消息错误:', error);
    
    // 移除"分析中"的消息（如果存在）
    if (chatHistory.value.length > 0 && chatHistory.value[chatHistory.value.length - 1].content.includes('正在分析')) {
      chatHistory.value.pop();
    }
    
    let errorMessage = '发送失败，请重试';
    if (error instanceof Error) {
      errorMessage = error.message;
    }
    
    // 添加错误消息到聊天历史
    chatHistory.value.push({
      role: 'assistant',
      content: `❌ ${errorMessage}`,
      timestamp: new Date()
    });
    
  } finally {
    isSending.value = false;
  }
};

// 处理输入框回车事件
const handleInputKeydown = (event: KeyboardEvent) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault();
    // 只有在有内容、选中图片或选中文件时才发送
    if (userInput.value.trim() || selectedImage.value || selectedFile.value) {
      handleSendMessage();
    }
  }
};

// 清空对话历史
const clearChatHistory = () => {
  chatHistory.value = [];
  currentAnswer.value = '';
};

// 处理示例问题点击
const handleQuestionClick = (question: string) => {
  userInput.value = question;
};

// 处理照片分析 - 修改为直接在页面显示
const handlePhotoAnalysis = async (file: File) => {
  try {
    // 文件类型验证
    if (!file.type.startsWith('image/')) {
      alert('请选择图片文件（支持 JPG、PNG、GIF 等格式）');
      return;
    }

    // 文件大小验证
    if (file.size > 10 * 1024 * 1024) {
      alert('图片文件大小不能超过10MB，请选择较小的图片');
      return;
    }

    // 支持的图片格式验证
    const supportedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
    if (!supportedTypes.includes(file.type)) {
      alert('不支持的图片格式，请选择 JPG、PNG、GIF 或 WebP 格式的图片');
      return;
    }

    isAnalyzing.value = true;
    
    // 显示图片预览
    const imageDataUrl = await convertImageToBase64(file);
    
    // 先添加用户上传的图片到聊天历史
    chatHistory.value.push({
      role: 'user',
      content: `📷 上传了图片：${file.name}`,
      timestamp: new Date(),
      imageUrl: imageDataUrl // 添加图片URL字段
    });
    
    console.log('开始分析图片:', {
      name: file.name,
      size: `${(file.size / 1024 / 1024).toFixed(2)}MB`,
      type: file.type
    });
    
    // 添加图片上传成功的消息（使用打字机效果）
    const messageIndex = chatHistory.value.length;
    const successMessage = `📷 图片上传成功！您可以在输入框中描述您想了解的内容，我会结合图片为您解答。`;
    
    chatHistory.value.push({
      role: 'assistant',
      content: '',
      timestamp: new Date()
    });
    
    // 启动打字机效果
          typewriterEffect(successMessage, messageIndex, 30);
          
          // 标记消息完成
          setTimeout(() => {
            if (chatHistory.value[messageIndex]) {
              chatHistory.value[messageIndex].content = successMessage;
              nextTick(() => {
                const messageElement = document.querySelector(`.message:nth-child(${messageIndex + 1}) .message-text`);
                if (messageElement) {
                  messageElement.classList.add('message-complete');
                }
              });
            }
          }, successMessage.length * 30 + 100);
    
    console.log('图片上传完成');
    
    // 滚动到底部显示结果
    nextTick(() => {
      scrollToBottom();
    });
    
  } catch (error) {
    console.error('照片上传错误:', error);
    
    let errorMessage = '照片上传失败';
    if (error instanceof Error) {
      errorMessage = error.message;
    }
    
    // 添加错误消息到聊天历史
    chatHistory.value.push({
      role: 'assistant',
      content: `❌ ${errorMessage}`,
      timestamp: new Date()
    });
    
  } finally {
    isAnalyzing.value = false;
  }
};

// 触发文件选择
const triggerFileSelect = () => {
  fileInputRef.value?.click();
};

// 处理文件选择
const handleFileSelect = async (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];
  if (file) {
    // 文件类型验证
    if (!file.type.startsWith('image/')) {
      alert('请选择图片文件（支持 JPG、PNG、GIF 等格式）');
      return;
    }

    // 文件大小验证
    if (file.size > 10 * 1024 * 1024) {
      alert('图片文件大小不能超过10MB，请选择较小的图片');
      return;
    }

    // 支持的图片格式验证
    const supportedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
    if (!supportedTypes.includes(file.type)) {
      alert('不支持的图片格式，请选择 JPG、PNG、GIF 或 WebP 格式的图片');
      return;
    }

    // 保存选中的图片，不立即发送
    selectedImage.value = file;
    selectedImagePreview.value = await convertImageToBase64(file);
  }
  // 清空input值，允许重复选择同一文件
  target.value = '';
};





// 点击加号按钮
const handlePlusClick = () => {
  showFunctionMenu.value = !showFunctionMenu.value;
};

// 打开历史记录弹窗
const openHistoryModal = () => {
  showHistoryModal.value = true;
  isHistoryClosing.value = false;
};

// 关闭历史记录弹窗
const closeHistoryModal = () => {
  isHistoryClosing.value = true;
  
  // 等待动画完成后再隐藏弹窗
  setTimeout(() => {
    showHistoryModal.value = false;
    isHistoryClosing.value = false;
    historySearchKeyword.value = '';
  }, 300); // 300ms对应CSS动画时长
};

// 清空所有历史记录
const clearAllHistory = () => {
  if (confirm('确定要清空所有历史记录吗？')) {
    searchHistory.value = [];
    localStorage.removeItem('searchHistory');
  }
};

// 删除单条历史记录
const deleteHistoryItem = (id: string) => {
  if (confirm('确定要删除这条历史记录吗？')) {
    searchHistory.value = searchHistory.value.filter(item => item.id !== id);
    saveHistoryToStorage();
  }
};

// 点击历史记录项 - 显示完整对话
const selectHistoryItem = (item: any) => {
  // 添加用户查询到聊天历史
  chatHistory.value.push({
    role: 'user',
    content: item.query,
    timestamp: item.timestamp
  });
  
  // 添加AI回复到聊天历史
  chatHistory.value.push({
    role: 'assistant',
    content: item.result,
    timestamp: item.timestamp
  });
  
  // 关闭历史记录弹窗
  closeHistoryModal();
  
  // 滚动到底部显示新添加的内容
  nextTick(() => {
    scrollToBottom();
  });
};

// 保存历史记录到本地存储
const saveHistoryToStorage = () => {
  localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value));
};

// 从本地存储加载历史记录
const loadHistoryFromStorage = () => {
  const saved = localStorage.getItem('searchHistory');
  if (saved) {
    try {
      searchHistory.value = JSON.parse(saved).map((item: any) => ({
        ...item,
        timestamp: new Date(item.timestamp)
      }));
    } catch (e) {
      console.error('加载历史记录失败:', e);
    }
  }
};

// 添加搜索记录
const addSearchHistory = (type: 'text' | 'image' | 'file', query: string, result: string) => {
  const historyItem = {
    id: Date.now().toString(),
    type,
    query,
    result: result.substring(0, 200) + (result.length > 200 ? '...' : ''),
    timestamp: new Date()
  };
  
  searchHistory.value.unshift(historyItem);
  
  // 限制历史记录数量
  if (searchHistory.value.length > 100) {
    searchHistory.value = searchHistory.value.slice(0, 100);
  }
  
  saveHistoryToStorage();
};

// 过滤历史记录
const filteredHistory = computed(() => {
  if (!historySearchKeyword.value.trim()) {
    return searchHistory.value;
  }
  
  const query = historySearchKeyword.value.toLowerCase();
  return searchHistory.value.filter(item => 
    item.query.toLowerCase().includes(query) ||
    item.result.toLowerCase().includes(query)
  );
});

// 获取历史记录类型图标
const getHistoryTypeIcon = (type: string) => {
  switch (type) {
    case 'image': return '📷';
    case 'file': return '📁';
    default: return '💬';
  }
};

// 格式化时间
const formatHistoryTime = (timestamp: Date) => {
  const now = new Date();
  const diff = now.getTime() - timestamp.getTime();
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));
  
  if (days === 0) {
    return timestamp.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
  } else if (days === 1) {
    return '昨天 ' + timestamp.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
  } else if (days < 7) {
    return days + '天前';
  } else {
    return timestamp.toLocaleDateString('zh-CN');
  }
};

// 打开摄像头（支持录像）
const openCamera = async () => {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ 
      video: { 
        width: { ideal: 1280 },
        height: { ideal: 720 },
        facingMode: 'environment' // 优先使用后置摄像头
      },
      audio: true // 添加音频支持用于录像
    });
    
    cameraStream.value = stream;
    isCameraOpen.value = true;
    
    // 等待DOM更新后设置视频流
    await nextTick();
    if (videoRef.value) {
      videoRef.value.srcObject = stream;
      await videoRef.value.play();
    }
  } catch (error) {
    console.error('无法访问摄像头:', error);
    alert('无法访问摄像头，请检查权限设置');
  }
};

// 重置录制状态
const resetRecordingState = () => {
  isVideoRecording.value = false;
  mediaRecorder.value = null;
  recordedChunks.value = [];
  recordingTime.value = 0;
  if (recordingTimer.value) {
    clearInterval(recordingTimer.value);
    recordingTimer.value = null;
  }
};

// 开始录像
const startVideoRecording = () => {
  if (!cameraStream.value) {
    alert('摄像头未准备就绪');
    return;
  }

  try {
    const options = {
      mimeType: 'video/webm;codecs=vp9,opus'
    };
    
    // 检查浏览器支持的格式
    if (!MediaRecorder.isTypeSupported(options.mimeType)) {
      options.mimeType = 'video/webm';
      if (!MediaRecorder.isTypeSupported(options.mimeType)) {
        options.mimeType = 'video/mp4';
      }
    }

    mediaRecorder.value = new MediaRecorder(cameraStream.value, options);
    recordedChunks.value = [];
    
    mediaRecorder.value.ondataavailable = (event) => {
      if (event.data.size > 0) {
        recordedChunks.value.push(event.data);
      }
    };
    
    mediaRecorder.value.onstop = async () => {
          const blob = new Blob(recordedChunks.value, { type: 'video/webm' });
          const file = new File([blob], `video-${Date.now()}.webm`, { type: 'video/webm' });
          
          // 设置选中的视频
          selectedVideo.value = file;
          selectedVideoPreview.value = URL.createObjectURL(blob);
          
          // 关闭摄像头
          closeCamera();
          
          console.log('录像完成:', file);
          alert(`录像完成！时长: ${formatRecordingTime(recordingTime.value)}`);
          
          resetRecordingState();
        };
    
    mediaRecorder.value.start();
    isVideoRecording.value = true;
    recordingTime.value = 0;
    
    // 开始计时
    recordingTimer.value = window.setInterval(() => {
      recordingTime.value++;
    }, 1000) as unknown as number;
    
  } catch (error) {
    console.error('录像启动失败:', error);
    alert('录像功能启动失败');
  }
};

// 停止录像
const stopVideoRecording = () => {
  if (mediaRecorder.value && isVideoRecording.value) {
    mediaRecorder.value.stop();
    if (recordingTimer.value) {
      clearInterval(recordingTimer.value);
      recordingTimer.value = null;
    }
  }
};

// 格式化录制时间
const formatRecordingTime = (seconds: number): string => {
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
};

// 关闭摄像头（更新版本）
const closeCamera = () => {
  // 如果正在录像，先停止录像
  if (isVideoRecording.value) {
    stopVideoRecording();
  }
  
  if (cameraStream.value) {
    cameraStream.value.getTracks().forEach(track => track.stop());
    cameraStream.value = null;
  }
  isCameraOpen.value = false;
  resetRecordingState();
};

// 拍照并转换为文件
const takePicture = async () => {
  if (!videoRef.value || !canvasRef.value) {
    alert('摄像头未准备就绪');
    return;
  }

  const video = videoRef.value;
  const canvas = canvasRef.value;
  const context = canvas.getContext('2d');
  
  if (!context) {
    alert('无法获取画布上下文');
    return;
  }

  // 设置画布尺寸与视频一致
  canvas.width = video.videoWidth;
  canvas.height = video.videoHeight;
  
  // 将视频帧绘制到画布
  context.drawImage(video, 0, 0, canvas.width, canvas.height);
  
  // 将画布内容转换为Blob
  canvas.toBlob(async (blob) => {
    if (blob) {
      // 创建File对象
      const file = new File([blob], `camera-${Date.now()}.jpg`, { type: 'image/jpeg' });
      
      // 设置选中的图片
      selectedImage.value = file;
      selectedImagePreview.value = await convertImageToBase64(file);
      
      // 关闭摄像头
      closeCamera();
      
      console.log('拍照成功，图片已准备发送');
    }
  }, 'image/jpeg', 0.9);
};

// 处理文件分析选择
const handleFileAnalysis = () => {
  fileInputForAnalysisRef.value?.click();
  showFunctionMenu.value = false;
};

// 处理文件分析选择事件
const handleFileAnalysisSelect = async (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];
  if (file) {
    // 文件大小验证
    if (file.size > 20 * 1024 * 1024) {
      alert('文件大小不能超过20MB，请选择较小的文件');
      return;
    }

    // 保存选中的文件
    selectedFile.value = file;
    
    // 如果是图片，生成预览
    if (file.type.startsWith('image/')) {
      selectedFilePreview.value = await convertImageToBase64(file);
    } else {
      selectedFilePreview.value = '';
    }
    
    // 提示用户输入问题
    // userInput.value = `请分析这个文件：${file.name}，`;
    
    // 聚焦到输入框
    nextTick(() => {
      const inputElement = document.querySelector('.question-input') as HTMLInputElement;
      if (inputElement) {
        inputElement.focus();
        // 将光标移到末尾
        inputElement.setSelectionRange(inputElement.value.length, inputElement.value.length);
      }
    });
  }
  // 清空input值
  target.value = '';
};

// 处理功能菜单项点击
const handleMenuItemClick = (action: string) => {
  console.log(`点击了${action}功能`);
  showFunctionMenu.value = false;
  
  switch (action) {
    case "photo":
      // 处理照片选择逻辑（仅限图片）
      triggerFileSelect();
      break;
    case "camera":
      // 处理拍照逻辑
      openCamera();
      break;
    case "fileAnalysis":
      // 处理文件分析逻辑
      handleFileAnalysis();
      break;

    case "database":
      // 处理资料库逻辑
      alert('资料库功能开发中...');
      break;
  }
};

// ... existing code ...

// 点击其他区域关闭菜单
const handleOverlayClick = () => {
  showFunctionMenu.value = false;
};

// 清除选中的图片
const clearSelectedImage = () => {
  selectedImage.value = null;
  selectedImagePreview.value = '';
};

// 聊天消息容器引用
const chatMessagesRef = ref<HTMLElement | null>(null);
// 滚动容器引用
const scrollableContainer = ref<HTMLElement | null>(null);

// 平滑滚动到指定位置
const scrollToPosition = (position: number) => {
  if (scrollableContainer.value) {
    scrollableContainer.value.scrollTo({
      top: position,
      behavior: 'smooth'
    });
  }
};

// 滚动到顶部
const scrollToTop = () => {
  scrollToPosition(0);
};

// 滚动到底部
const scrollToBottom = () => {
  if (scrollableContainer.value) {
    scrollToPosition(scrollableContainer.value.scrollHeight);
  }
  if (chatMessagesRef.value) {
    chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight;
  }
};

// 监听聊天历史变化，自动滚动到底部
watch(chatHistory, () => {
  nextTick(() => {
    scrollToBottom();
  });
}, { deep: true });

// 监听发送状态变化，自动滚动到底部
watch(isSending, () => {
  nextTick(() => {
    scrollToBottom();
  });
});

// 语音识别相关状态
const isRecording = ref(false);
const isPaused = ref(false);
const speechPreview = ref('');
const speechError = ref('');
const recognition = ref<any>(null);

// 消息操作相关状态
const editingMessageIndex = ref(-1);
const editingContent = ref('');
const showMessageMenu = ref(-1); // 显示操作菜单的消息索引

// 语音播放相关状态
const speechSynthesis = ref<any>(null);
const currentUtterance = ref<any>(null);
const isSpeaking = ref(false);
const isPausedSpeech = ref(false); // 重命名避免与语音识别的isPaused冲突
const speechRate = ref(1); // 语速
const speechPitch = ref(1); // 音调
const speechVolume = ref(1); // 音量
const currentSpeakingMessageIndex = ref(-1); // 当前播放的消息索引
const showSpeechSettings = ref(false); // 控制语音设置弹窗显示

// 语音设置
const speechSettings = ref({
  enabled: true, // 是否启用语音播放
  autoPlay: false, // 是否自动播放新消息
  voice: null, // 选择的语音
  rate: 1,
  pitch: 1,
  volume: 1
});


// 可用的语音列表
const availableVoices = ref<any[]>([]);

// 初始化语音识别
const initSpeechRecognition = () => {
  if (!('webkitSpeechRecognition' in window) && !('SpeechRecognition' in window)) {
    console.warn('浏览器不支持语音识别');
    return null;
  }
  
  const SpeechRecognition = (window as any).SpeechRecognition || (window as any).webkitSpeechRecognition;
  const recognitionInstance = new SpeechRecognition();
  
  // 强制使用本地识别，减少网络依赖
  if (recognitionInstance.serviceURI !== undefined) {
    recognitionInstance.serviceURI = null;
  }
  
  // 针对Safari和移动设备的优化配置
  const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
  
  // Safari和移动设备使用更保守的设置
  if (isSafari || isMobile) {
    recognitionInstance.continuous = false;  // 关闭连续识别
    recognitionInstance.interimResults = false;  // 关闭临时结果
  } else {
    recognitionInstance.continuous = true;
    recognitionInstance.interimResults = true;
  }
  
  recognitionInstance.lang = 'zh-CN';
  recognitionInstance.maxAlternatives = 1;  // 限制备选结果数量
  
  recognitionInstance.onstart = () => {
    console.log('语音识别开始');
    isRecording.value = true;
    isPaused.value = false;
    speechError.value = '';
  };
  
  recognitionInstance.onresult = (event: any) => {
    let finalTranscript = '';
    let interimTranscript = '';
    
    for (let i = event.resultIndex; i < event.results.length; i++) {
      const transcript = event.results[i][0].transcript;
      if (event.results[i].isFinal) {
        finalTranscript += transcript;
      } else {
        interimTranscript += transcript;
      }
    }
    
    // 实时显示临时结果在输入框中
    if (interimTranscript) {
      speechPreview.value = interimTranscript;
      // 可选：也在输入框中显示临时结果
      userInput.value = interimTranscript;
    }
    
    // 最终结果确认后填入输入框
    if (finalTranscript) {
      userInput.value = finalTranscript;
      speechPreview.value = '';
      
      // 可选：自动发送或提示用户确认
      // handleSendMessage(); // 自动发送
    }
  };
  
  recognitionInstance.onerror = (event: any) => {
    console.error('语音识别错误:', event.error);
    let errorMessage = '语音识别失败';
    let shouldRetry = false;
    
    switch (event.error) {
      case 'no-speech':
        errorMessage = '未检测到语音，请重试';
        shouldRetry = true;
        break;
      case 'audio-capture':
        errorMessage = '无法访问麦克风，请检查权限';
        break;
      case 'not-allowed':
        errorMessage = '麦克风权限被拒绝';
        break;
      case 'network':
        // 针对网络错误的特殊处理
        if (isSafari || isMobile) {
          errorMessage = '网络连接不稳定，建议切换到本地识别模式';
        } else {
          errorMessage = '网络错误，正在重试...';
          shouldRetry = true;
        }
        break;
      case 'service-not-allowed':
        errorMessage = '语音服务不可用，请稍后重试';
        break;
      default:
        errorMessage = `语音识别错误: ${event.error}`;
    }
    
    speechError.value = errorMessage;
    isRecording.value = false;
    isPaused.value = false;
    
    // 网络错误时自动重试（最多3次）
    if (shouldRetry && event.error === 'network') {
      const retryCount = (recognitionInstance as any).retryCount || 0;
      if (retryCount < 3) {
        (recognitionInstance as any).retryCount = retryCount + 1;
        setTimeout(() => {
          console.log(`网络错误，第${retryCount + 1}次重试`);
          startSpeechRecognition();
        }, 1000 * (retryCount + 1)); // 递增延迟
        return;
      }
    }
    
    // 清除错误信息
    setTimeout(() => {
      speechError.value = '';
    }, 5000);
  };
  
  recognitionInstance.onend = () => {
    console.log('语音识别结束');
    isRecording.value = false;
    isPaused.value = false;
    speechPreview.value = '';
    
    // 如果有识别结果，显示确认提示
    // if (userInput.value.trim()) {
    //   // 可以添加一个短暂的成功提示
    //   speechError.value = '✅ 语音识别完成';
    //   setTimeout(() => {
    //     speechError.value = '';
    //   }, 2000);
    // }
  };
  
  return recognitionInstance;
};

// 开始语音识别
const startSpeechRecognition = () => {
  try {
    if (!recognition.value) {
      recognition.value = initSpeechRecognition();
    }
    
    if (!recognition.value) {
      speechError.value = '您的浏览器不支持语音识别功能';
      return;
    }
    
    recognition.value.start();
  } catch (error) {
    console.error('启动语音识别失败:', error);
    speechError.value = '启动语音识别失败，请重试';
  }
};

// 停止语音识别
const stopSpeechRecognition = () => {
  if (recognition.value && isRecording.value) {
    recognition.value.stop();
  }
};

// 暂停语音识别
const pauseSpeechRecognition = () => {
  if (recognition.value && isRecording.value) {
    recognition.value.stop();
    isPaused.value = true;
    isRecording.value = false;
  }
};

// 恢复语音识别
const resumeSpeechRecognition = () => {
  if (isPaused.value) {
    startSpeechRecognition();
    isPaused.value = false;
  }
};

// 处理语音按钮点击
const handleVoiceClick = () => {
  if (isRecording.value) {
    stopSpeechRecognition();
  } else if (isPaused.value) {
    resumeSpeechRecognition();
  } else {
    startSpeechRecognition();
  }
};

// 初始化语音合成
const initSpeechSynthesis = () => {
  if ('speechSynthesis' in window) {
    speechSynthesis.value = window.speechSynthesis;
    
    // 获取可用语音
    const loadVoices = () => {
      availableVoices.value = speechSynthesis.value.getVoices();
      // 优先选择中文语音
      const chineseVoice = availableVoices.value.find(voice => 
        voice.lang.includes('zh') || voice.name.includes('Chinese')
      );
      if (chineseVoice && !speechSettings.value.voice) {
        speechSettings.value.voice = chineseVoice;
      }
    };
    
    loadVoices();
    speechSynthesis.value.onvoiceschanged = loadVoices;
  } else {
    console.warn('浏览器不支持语音合成功能');
  }
};

// 播放文本
const speakText = (text: string, messageIndex = -1) => {
  if (!speechSynthesis.value || !speechSettings.value.enabled) {
    return;
  }
  
  // 停止当前播放
  stopSpeaking();
  
  // 清理文本（移除emoji和特殊字符）
  const cleanText = text
    .replace(/[📷🔍❌👋]/g, '') // 移除emoji
    .replace(/图片分析结果：/g, '')
    .replace(/正在分析您上传的图片，请稍候.../g, '')
    .trim();
  
  if (!cleanText) return;
  
  const utterance = new SpeechSynthesisUtterance(cleanText);
  
  // 设置语音参数
  if (speechSettings.value.voice) {
    utterance.voice = speechSettings.value.voice;
  }
  utterance.rate = speechSettings.value.rate;
  utterance.pitch = speechSettings.value.pitch;
  utterance.volume = speechSettings.value.volume;
  
  // 事件监听
  utterance.onstart = () => {
    isSpeaking.value = true;
    isPausedSpeech.value = false;
    currentSpeakingMessageIndex.value = messageIndex;
  };
  
  utterance.onend = () => {
    isSpeaking.value = false;
    isPausedSpeech.value = false;
    currentSpeakingMessageIndex.value = -1;
    currentUtterance.value = null;
  };
  
  utterance.onerror = (event) => {
    console.error('语音播放错误:', event.error);
    isSpeaking.value = false;
    isPausedSpeech.value = false;
    currentSpeakingMessageIndex.value = -1;
  };
  
  currentUtterance.value = utterance;
  speechSynthesis.value.speak(utterance);
};



// 停止播放
const stopSpeaking = () => {
  if (speechSynthesis.value) {
    speechSynthesis.value.cancel();
    isSpeaking.value = false;
    isPausedSpeech.value = false;
    currentSpeakingMessageIndex.value = -1;
    currentUtterance.value = null;
  }
};



// 从localStorage加载语音设置
const loadSpeechSettings = () => {
  const saved = localStorage.getItem('speechSettings');
  if (saved) {
    try {
      const settings = JSON.parse(saved);
      speechSettings.value = { ...speechSettings.value, ...settings };
    } catch (e) {
      console.error('加载语音设置失败:', e);
    }
  }
};

// 保存语音设置
const saveSpeechSettings = () => {
  localStorage.setItem('speechSettings', JSON.stringify(speechSettings.value));
};

// 获取输入框占位符文本
const getInputPlaceholder = () => {
  // if (isRecording.value) {
  //   return '正在录音中，请说话...';
  // }
  if (speechPreview.value) {
    return ' 识别中...';
  }
  if (selectedFile.value) {
    return '为文件添加分析要求...';
  }
  if (selectedImage.value) {
    return '为图片添加描述或直接发送进行OCR识别...';
  }
  return '有什么健康问题吗';
};

// 监听新消息，自动播放
watch(chatHistory, (newHistory, oldHistory) => {
  if (speechSettings.value.autoPlay && newHistory.length > oldHistory.length) {
    const lastMessage = newHistory[newHistory.length - 1];
    if (lastMessage.role === 'assistant') {
      nextTick(() => {
        speakText(lastMessage.content, newHistory.length - 1);
      });
    }
  }
}, { deep: true });

// 组件挂载时初始化
onMounted(() => {
  initSpeechSynthesis();
  loadSpeechSettings();
  loadHistoryFromStorage();
});

// 删除消息
const deleteMessage = (index: number) => {
  if (confirm('确定要删除这条消息吗？')) {
    chatHistory.value.splice(index, 1);
    showMessageMenu.value = -1;
  }
};

// 复制消息内容
const copyMessage = async (content: string) => {
  try {
    await navigator.clipboard.writeText(content);
    alert('消息已复制到剪贴板');
  } catch (err) {
    // 降级方案
    const textArea = document.createElement('textarea');
    textArea.value = content;
    document.body.appendChild(textArea);
    textArea.select();
    document.execCommand('copy');
    document.body.removeChild(textArea);
    alert('消息已复制到剪贴板');
  }
  showMessageMenu.value = -1;
};

// 开始编辑消息
const startEditMessage = (index: number, content: string) => {
  editingMessageIndex.value = index;
  editingContent.value = content;
  showMessageMenu.value = -1;
};

// 保存编辑的消息
const saveEditMessage = () => {
  if (editingContent.value.trim() && editingMessageIndex.value >= 0) {
    chatHistory.value[editingMessageIndex.value].content = editingContent.value.trim();
    editingMessageIndex.value = -1;
    editingContent.value = '';
  }
};

// 取消编辑
const cancelEditMessage = () => {
  editingMessageIndex.value = -1;
  editingContent.value = '';
};

// 切换消息菜单显示
const toggleMessageMenu = (index: number) => {
  showMessageMenu.value = showMessageMenu.value === index ? -1 : index;
};

// 点击其他地方关闭菜单
const closeMessageMenu = () => {
  showMessageMenu.value = -1;
};



// 清理所有定时器的函数
const clearAllTimers = () => {
  // 清理录制定时器
  if (recordingTimer.value) {
    clearInterval(recordingTimer.value);
    recordingTimer.value = null;
  }
  
  // 清理所有打字机效果定时器
  activeTimers.value.forEach(timer => {
    clearInterval(timer);
  });
  activeTimers.value.clear();
  
  // 清理其他可能的定时器
  // 如果有其他定时器，在这里添加清理逻辑
};

// 组件卸载时停止播放和清理定时器
onUnmounted(() => {
  stopSpeaking();
  clearAllTimers();
});

// 添加导航栏数据
const tabbar = [
  { icon: 'home' },
  { icon: 'msg' },
  { icon: 'calendar' },
  { icon: 'bell' },
  { icon: 'user' },
]

// 添加导航栏点击处理函数
const handleTabClick = (icon: string) => {
  switch (icon) {
    case 'home':
      router.push('/home');
      break;
    case 'msg':
      // 当前页面（AI）
      break;
    case 'calendar':
      router.push('/time-select');
      break;
    case 'bell':
      router.push('/lhx-patient-chat');
      break;
    case 'user':
      router.push('/medical-home');
      break;
  }
};

</script>

<template>
  <div class="home">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="header-left">
        <div class="menu-icon" @click="openHistoryModal">☰</div>
      </div>
      <div class="header-center">问一问</div>
      
      <!-- 语音设置按钮 -->
      <button class="speech-settings-btn" @click="showSpeechSettings = true" :title="speechSettings.enabled ? '语音已开启' : '语音已关闭'">
        <span v-if="speechSettings.enabled">🔊</span>
        <span v-else>🔇</span>
      </button>
      <span class="clear-btn" @click="clearChatHistory">🗑️</span>
      <div class="header-right">我的</div>
    </header>
    
    <!-- 可滚动的主内容区域 -->
    <div class="scrollable-container" ref="scrollableContainer">
      <main class="main-content">
        <!-- 健康提示卡片 -->
        <div class="health-tip-card">
          <div class="tip-content">{{ healthTip }}</div>
          <div class="tip-arrow">›</div>
        </div>

        <!-- 每日药物小常识 -->
        <div class="daily-medicine-tip">
          <div class="tip-icon">💡</div>
          <div class="tip-title">每日药物小常识</div>
        </div>
        <div class="medicine-info">
          <div class="medicine-title">{{ medicineInfo.title }}</div>
          <div class="medicine-content">{{ medicineInfo.content }}</div>
        </div>

        <!-- 问题建议区域 -->
        <div class="question-suggestion">
          <div class="suggestion-title">你可以这样问</div>
          <div class="suggestion-items">
            <div
              class="suggestion-item"
              v-for="(question, index) in exampleQuestions"
              :key="index"
              @click="handleQuestionClick(question)"
            >
              {{ question }}
            </div>
          </div>
        </div>
        
        <!-- AI对话区域 -->
        
          
          <div class="chat-messages" ref="chatMessagesRef">
            <!-- 当没有对话历史时显示欢迎信息 -->
            <div v-if="chatHistory.length === 0 && !isSending" class="welcome-message">
              <div class="welcome-text">👋 您好！我是您的AI健康助手，有什么健康问题可以问我哦～</div>
            </div>
            
            <div 
              v-for="(message, index) in chatHistory" 
              :key="index"
              :class="['message', message.role === 'user' ? 'user-message' : 'ai-message']"
              @click="closeMessageMenu"
            >
              <div class="message-content">
                <div v-if="message.imageUrl" class="message-image">
                  <img :src="message.imageUrl" alt="上传的图片" class="uploaded-image" />
                </div>
                
                <!-- 编辑模式 -->
                <div v-if="editingMessageIndex === index" class="message-edit">
                  <textarea 
                    v-model="editingContent"
                    class="edit-textarea"
                    @keydown.enter.ctrl="saveEditMessage"
                    @keydown.esc="cancelEditMessage"
                  ></textarea>
                  <div class="edit-controls">
                    <button @click="saveEditMessage" class="save-btn">保存</button>
                    <button @click="cancelEditMessage" class="cancel-btn">取消</button>
                  </div>
                </div>
                
                <!-- 正常显示模式 -->
                <div v-else :class="['message-text', { 'message-complete': message.content.length > 0 }]">{{ message.content }}</div>
                
                <!-- 消息操作菜单 -->
                <div class="message-actions">
                  <button 
                    @click.stop="toggleMessageMenu(index)"
                    class="message-menu-btn"
                    title="更多操作"
                  >
                    ⋯
                  </button>
                  
                  <!-- 操作菜单 -->
                  <div v-if="showMessageMenu === index" class="message-menu" @click.stop>
                    <button @click="copyMessage(message.content)" class="menu-item">
                      📋 复制
                    </button>
                    <button 
                      v-if="message.role === 'user'"
                      @click="startEditMessage(index, message.content)"
                      class="menu-item"
                    >
                      ✏️ 编辑
                    </button>
                    <button @click="deleteMessage(index)" class="menu-item delete">
                      🗑️ 删除
                    </button>
                  </div>
                </div>
                
                <!-- AI消息的语音播放控制 -->
                <div v-if="message.role === 'assistant'" class="message-controls">
                  <!-- 播放按钮（仅在未播放时显示） -->
                  <button 
                    v-if="currentSpeakingMessageIndex !== index || !isSpeaking"
                    @click="speakText(message.content, index)"
                    class="speech-btn"
                    title="播放语音"
                  >
                    🔊
                  </button>
                  
                  <!-- 停止按钮（仅在播放时显示） -->
                  <button 
                    v-if="currentSpeakingMessageIndex === index && isSpeaking"
                    @click="stopSpeaking"
                    class="stop-btn"
                    title="停止播放"
                  >
                    ⏹️
                  </button>
                </div>
                <div class="message-time">{{ message.timestamp.toLocaleTimeString() }}</div>
              </div>
            </div>
            
            <!-- 加载状态 -->
            <div v-if="isSending" class="message ai-message">
              <div class="message-content">
                <div class="typing-indicator">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
              </div>
            </div>
  
        </div>

        <!-- 底部功能按钮 -->
    
      </main>
    </div>

    <!-- 固定在底部的输入框 -->
    <div class="input-container">
      <!-- 图片预览区域 -->
      <div v-if="selectedImage" class="image-preview-container">
        <div class="image-preview">
          <img :src="selectedImagePreview" alt="选中的图片" class="preview-image" />
          <div class="image-info">
            <div class="image-name">{{ selectedImage.name }}</div>
            <div class="image-size">{{ (selectedImage.size / 1024 / 1024).toFixed(2) }}MB</div>
          </div>
          <button @click="clearSelectedImage" class="remove-image-btn">×</button>
        </div>
        <div class="analysis-tip">
          💡 提示：您可以在输入框中添加文字描述，AI将结合图片内容和您的描述进行更准确的分析
        </div>
      </div>
      
      <!-- 文件预览区域 -->
      <div v-if="selectedFile" class="file-preview-container">
        <div class="file-preview">
          <div v-if="selectedFilePreview" class="file-image-preview">
            <img :src="selectedFilePreview" alt="文件预览" class="preview-image" />
          </div>
          <div v-else class="file-icon">
            📄
          </div>
          <div class="file-info">
            <div class="file-name">{{ selectedFile.name }}</div>
            <div class="file-size">{{ (selectedFile.size / 1024 / 1024).toFixed(2) }}MB</div>
            <div class="file-type">{{ selectedFile.type || '未知类型' }}</div>
          </div>
          <button @click="selectedFile = null; selectedFilePreview = ''" class="remove-file-btn">×</button>
        </div>
      </div>
      
      <!-- 文件预览区域 -->
      <div v-if="selectedFile" class="file-preview-container">
        <div class="file-preview">
          <div v-if="selectedFilePreview" class="file-image-preview">
            <img :src="selectedFilePreview" alt="文件预览" class="preview-image" />
          </div>
          <div v-else class="file-icon">
            📄
          </div>
          <div class="file-info">
            <div class="file-name">{{ selectedFile.name }}</div>
            <div class="file-size">{{ (selectedFile.size / 1024 / 1024).toFixed(2) }}MB</div>
            <div class="file-type">{{ selectedFile.type || '未知类型' }}</div>
          </div>
          <button @click="selectedFile = null; selectedFilePreview = ''" class="remove-file-btn">×</button>
        </div>
      </div>
      
      <div class="input-row">
        <div class="input-icon" @click="handlePlusClick">
          <img src="/public/加号.png" style="width: 20px; height: 20px; cursor: pointer;" />
        </div>
        <input
          type="text"
          class="question-input"
          :class="{ 'speech-input': isRecording || speechPreview }"
          :placeholder="getInputPlaceholder()"
          v-model="userInput"
          @keydown="handleInputKeydown"
          :disabled="isSending"
        />
        <button 
          class="send-btn"
          @click="handleSendMessage"
          :disabled="(!userInput.trim() && !selectedImage && !selectedFile) || isSending"
        >
          {{ isSending ? '发送' : '发送' }}
             </button>
        <!-- 语音按钮 - 简化版本 -->
        <div class="voice-icon" @click="handleVoiceClick" :class="{ recording: isRecording }">
          <svg v-if="!isRecording" viewBox="0 0 24 24" width="20" height="20">
            <path fill="currentColor" d="M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3z"/>
            <path fill="currentColor" d="M17 11c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z"/>
          </svg>
          <svg v-else viewBox="0 0 24 24" width="20" height="20">
            <circle fill="#ff4444" cx="12" cy="12" r="8"/>
            <rect fill="white" x="9" y="9" width="6" height="6" rx="1"/>
          </svg>
        </div>
      </div>
      
      <!-- 语音错误提示 -->
      <div v-if="speechError" class="speech-error">
        {{ speechError }}
      </div>
      
      <!-- 语音状态提示 -->
      <!-- <div v-if="isRecording" class="speech-status">
        🎤 正在录音，请说话...
      </div> -->
    </div>



    <!-- 隐藏的文件输入框 -->
    <input
      ref="fileInputRef"
      type="file"
      accept="image/*"
      style="display: none;"
      @change="handleFileSelect"
    />
    
    <!-- 隐藏的文件分析输入框 -->
    <input
      ref="fileInputForAnalysisRef"
      type="file"
      accept=".txt,.csv,.pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png,.gif,.webp,.bmp"
      style="display: none;"
      @change="handleFileAnalysisSelect"
    />
    


    <!-- 功能菜单遮罩层 -->
    <div 
      v-if="showFunctionMenu" 
      class="menu-overlay" 
      @click="handleOverlayClick"
    ></div>

    <!-- 功能菜单 -->
    <div v-if="showFunctionMenu" class="function-menu">
      <div 
        v-for="item in functionMenuItems" 
        :key="item.action"
        class="menu-item"
        @click="handleMenuItemClick(item.action)"
      >
        <div class="menu-icon">{{ item.icon }}</div>
        <div class="menu-text">{{ item.text }}</div>
      </div>
    </div>

    <!-- 相机界面（全屏版本） -->
    <div v-if="isCameraOpen" class="camera-fullscreen">
      <!-- 视频预览 -->
      <video ref="videoRef" autoplay playsinline class="camera-video-fullscreen"></video>
      <canvas ref="canvasRef" style="display: none;"></canvas>
      
      <!-- 顶部控制栏 -->
      <div class="camera-top-bar">
        <button @click="closeCamera" class="close-camera-btn-fullscreen">
          <span class="close-icon">✕</span>
        </button>
        
        <!-- 录制状态指示器 -->
        <div v-if="isVideoRecording" class="recording-indicator">
          <div class="recording-dot"></div>
          <span class="recording-time">{{ formatRecordingTime(recordingTime) }}</span>
        </div>
      </div>
      
      <!-- 底部控制栏 -->
      <div class="camera-bottom-bar">
        <div class="camera-controls-wrapper">
          <!-- 拍照按钮 -->
          <div class="camera-action-container">
            <button 
              @click="takePicture" 
              class="modern-capture-btn"
              :disabled="isVideoRecording"
            >
              <div class="capture-icon">
                <svg viewBox="0 0 24 24" width="24" height="24">
                  <path fill="currentColor" d="M12 15.2l3.2-3.2-1.4-1.4-1.8 1.8-1.8-1.8-1.4 1.4 3.2 3.2zm0-6.2c-2.2 0-4 1.8-4 4s1.8 4 4 4 4-1.8 4-4-1.8-4-4-4zm0-3c-1.1 0-2 .9-2 2h4c0-1.1-.9-2-2-2z"/>
                  <path fill="currentColor" d="M20 4h-3.17l-1.24-1.35c-.37-.41-.91-.65-1.47-.65H9.88c-.56 0-1.1.24-1.47.65L7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2z"/>
                </svg>
              </div>
              <span class="btn-label">拍照</span>
            </button>
          </div>
          
          <!-- 录像按钮 -->
          <div class="camera-action-container">
            <button 
              @click="isVideoRecording ? stopVideoRecording() : startVideoRecording()" 
              :class="['modern-record-btn', { 'recording': isVideoRecording }]"
            >
              <div class="record-icon">
                <svg v-if="!isVideoRecording" viewBox="0 0 24 24" width="24" height="24">
                  <circle fill="currentColor" cx="12" cy="12" r="8"/>
                </svg>
                <svg v-else viewBox="0 0 24 24" width="24" height="24">
                  <rect fill="currentColor" x="6" y="6" width="12" height="12" rx="2"/>
                </svg>
              </div>
              <span class="btn-label">{{ isVideoRecording ? '停止' : '录像' }}</span>
            </button>
          </div>
        </div>
      </div>
      
      <!-- 功能说明 -->
      <div class="camera-instructions">
        <p v-if="!isVideoRecording">点击圆形按钮拍照，点击方形按钮录像</p>
        <p v-else>正在录像中，点击方形按钮停止录像</p>
      </div>
    </div>

    <!-- 语音设置弹窗 -->
    <div v-if="showSpeechSettings" class="speech-settings-overlay" @click="showSpeechSettings = false">
      <div class="speech-settings-modal" @click.stop>
        <div class="settings-header">
          <h3>语音设置</h3>
          <button class="close-btn" @click="showSpeechSettings = false">×</button>
        </div>
        
        <div class="settings-content">
          <!-- 启用语音 -->
          <div class="setting-item">
            <label class="switch-label">
              <input 
                type="checkbox" 
                v-model="speechSettings.enabled"
                @change="saveSpeechSettings"
              />
              <span class="switch-slider"></span>
              启用语音播放
            </label>
          </div>
          
          <!-- 自动播放 -->
          <div class="setting-item">
            <label class="switch-label">
              <input 
                type="checkbox" 
                v-model="speechSettings.autoPlay"
                @change="saveSpeechSettings"
                :disabled="!speechSettings.enabled"
              />
              <span class="switch-slider"></span>
              自动播放新消息
            </label>
          </div>
          
          <!-- 语音选择 -->
          <div class="setting-item" v-if="speechSettings.enabled">
            <label>选择语音</label>
            <select 
              v-model="speechSettings.voice"
              @change="saveSpeechSettings"
              class="voice-select"
            >
              <option 
                v-for="voice in availableVoices.filter(v => v.lang.includes('zh') || v.lang.includes('en'))"
                :key="voice.name"
                :value="voice"
              >
                {{ voice.name }} ({{ voice.lang }})
              </option>
            </select>
          </div>
          
          <!-- 语速控制 -->
          <div class="setting-item" v-if="speechSettings.enabled">
            <label>语速: {{ speechSettings.rate.toFixed(1) }}</label>
            <input 
              type="range" 
              min="0.5" 
              max="2" 
              step="0.1"
              v-model.number="speechSettings.rate"
              @input="saveSpeechSettings"
              class="range-slider"
            />
          </div>
          
          <!-- 音调控制 -->
          <div class="setting-item" v-if="speechSettings.enabled">
            <label>音调: {{ speechSettings.pitch.toFixed(1) }}</label>
            <input 
              type="range" 
              min="0.5" 
              max="2" 
              step="0.1"
              v-model.number="speechSettings.pitch"
              @input="saveSpeechSettings"
              class="range-slider"
            />
          </div>
          
          <!-- 音量控制 -->
          <div class="setting-item" v-if="speechSettings.enabled">
            <label>音量: {{ Math.round(speechSettings.volume * 100) }}%</label>
            <input 
              type="range" 
              min="0" 
              max="1" 
              step="0.1"
              v-model.number="speechSettings.volume"
              @input="saveSpeechSettings"
              class="range-slider"
            />
          </div>
          
          <!-- 测试播放 -->
          <div class="setting-item" v-if="speechSettings.enabled">
            <button 
              @click="speakText('这是语音测试，您好！')"
              class="test-speech-btn"
            >
              🎵 测试语音
            </button>
          </div>
        </div>
        
        <div class="settings-footer">
          <button @click="showSpeechSettings = false" class="confirm-btn">确定</button>
        </div>
      </div>
    </div>



    <!-- 历史记录弹窗 -->
    <div v-if="showHistoryModal" 
         class="history-modal-overlay" 
         :class="{ closing: isHistoryClosing }"
         @click="closeHistoryModal">
      <div class="history-modal" 
           :class="{ closing: isHistoryClosing }"
           @click.stop>
        <div class="history-header">
          <h3>📚 搜索历史</h3>
          <div class="history-actions">
            <input 
              v-model="historySearchKeyword" 
              placeholder="搜索历史记录..." 
              class="history-search-input"
            />
            <button @click="clearAllHistory" class="clear-all-btn">清空全部</button>
            <button @click="closeHistoryModal" class="close-btn">×</button>
          </div>
        </div>
        
        <div class="history-content">
          <div v-if="filteredHistory.length === 0" class="no-history">
            <div class="no-history-icon">📝</div>
            <div class="no-history-text">暂无搜索历史</div>
          </div>
          
          <div v-else class="history-list">
            <div 
              v-for="item in filteredHistory" 
              :key="item.id"
              class="history-item"
              @click="selectHistoryItem(item)"
            >
              <div class="history-item-header">
                <div class="history-type-icon">
                  <span v-if="item.type === 'text'">💬</span>
                  <span v-else-if="item.type === 'image'">📷</span>
                  <span v-else-if="item.type === 'file'">📁</span>
                </div>
                <div class="history-query">{{ item.query }}</div>
                <button @click.stop="deleteHistoryItem(item.id)" class="delete-history-btn">🗑️</button>
              </div>
              <div class="history-timestamp">{{ formatHistoryTime(item.timestamp) }}</div>
              <div v-if="item.result" class="history-result-preview">
                {{ item.result.substring(0, 100) }}{{ item.result.length > 100 ? '...' : '' }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部导航栏 -->
    <div class="tabbar-new">
      <div
        v-for="(tab, idx) in tabbar"
        :key="tab.icon"
        :class="['tabbar-item', { active: tab.icon === 'msg' }]"
        @click="handleTabClick(tab.icon)"
      >
        <span class="icon-wrap">
          <svg v-if="tab.icon === 'home'" width="28" height="28" viewBox="0 0 24 24" fill="none" :stroke="tab.icon === 'home' ? '#1877F2' : '#555'" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M3 11.5L12 4l9 7.5V20a1 1 0 0 1-1 1h-4a1 1 0 0 1-1-1v-4h-2v4a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V11.5z"/>
          </svg>
          <svg v-else-if="tab.icon === 'msg'" width="28" height="28" viewBox="0 0 24 24" fill="none" :stroke="tab.icon === 'msg' ? '#1877F2' : '#555'" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
          </svg>
          <svg v-else-if="tab.icon === 'calendar'" width="28" height="28" viewBox="0 0 24 24" fill="none" :stroke="tab.icon === 'calendar' ? '#1877F2' : '#555'" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <rect x="3" y="4" width="18" height="18" rx="4"/>
            <path d="M16 2v4M8 2v4M3 10h18"/>
          </svg>
          <span v-else-if="tab.icon === 'bell'" class="icon-bell-wrap">
            <svg width="28" height="28" viewBox="0 0 24 24" fill="none" :stroke="tab.icon === 'bell' ? '#1877F2' : '#555'" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <path d="M18 16v-5a6 6 0 0 0-12 0v5a2 2 0 0 1-2 2h16a2 2 0 0 1-2-2z"/>
              <path d="M13.73 21a2 2 0 0 1-3.46 0"/>
            </svg>
            <span class="dot"></span>
          </span>
          <svg v-else-if="tab.icon === 'user'" width="28" height="28" viewBox="0 0 24 24" fill="none" :stroke="tab.icon === 'user' ? '#1877F2' : '#555'" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <circle cx="12" cy="8" r="4"/>
            <path d="M4 20v-1a4 4 0 0 1 4-4h8a4 4 0 0 1 4 4v1"/>
          </svg>
        </span>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 全局样式 */
.home {
  font-family: Arial, sans-serif;
  max-width: 500px;
  margin: 0 auto;
  background-color: #f5f5f5;
  height: 100vh;
  display: flex;
  flex-direction: column;
  padding-bottom: 80px; /* 增加底部padding，避免被导航栏遮挡 */
}

/* 顶部导航栏 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background-color: white;
  border-bottom: 1px solid #eee;
  flex-shrink: 0;
  z-index: 10;
}

.header-center {
  font-size: 18px;
  font-weight: bold;
}

/* 可滚动容器 */
.scrollable-container {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  scroll-behavior: smooth;
  padding-bottom: 140px; /* 为底部输入框和导航栏留出空间 */
}

/* 自定义滚动条样式 */
.scrollable-container::-webkit-scrollbar {
  width: 8px;
}

.scrollable-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.scrollable-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
  transition: background 0.3s ease;
}

.scrollable-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 主内容区 */
.main-content {
  padding: 15px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

/* AI对话区域样式 */
.chat-area {
  background-color: white;
  border-radius: 12px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  min-height: 200px;
  max-height: 400px;
  display: flex;
  flex-direction: column;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  flex-shrink: 0;
}

.chat-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.clear-btn {
  background: none;
  border: 1px solid #ddd;
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  color: #666;
}

.clear-btn:hover {
  background-color: #f5f5f5;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding-right: 5px;
  scroll-behavior: smooth;
}

/* 聊天消息滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 欢迎消息样式 */
.welcome-message {
  text-align: center;
  padding: 20px;
  color: #666;
}

.welcome-text {
  font-size: 14px;
  line-height: 1.5;
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 12px;
  border: 1px solid #e9ecef;
}

.message {
  display: flex;
  margin-bottom: 10px;
}

.user-message {
  justify-content: flex-end;
}

.ai-message {
  justify-content: flex-start;
}

.message-content {
  max-width: 80%;
  padding: 10px 12px;
  border-radius: 12px;
  position: relative;
}

.user-message .message-content {
  background-color: #007bff;
  color: white;
}

.ai-message .message-content {
  background-color: #f1f1f1;
  color: #333;
}

.message-text {
  font-size: 14px;
  line-height: 1.4;
  margin-bottom: 4px;
}

.message-time {
  font-size: 11px;
  opacity: 0.7;
}

/* 打字指示器 */
.typing-indicator {
  display: flex;
  gap: 4px;
  align-items: center;
}

.typing-indicator span {
  width: 6px;
  height: 6px;
  background-color: #999;
  border-radius: 50%;
  animation: typing 1.4s infinite;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-10px);
  }
}

/* 打字机效果样式 */
.message-text {
  font-size: 14px;
  line-height: 1.4;
  margin-bottom: 4px;
  position: relative;
}

/* 打字机光标效果 - 只在打字过程中显示 */
.message-text::after {
  content: '';
  display: none;
  width: 2px;
  height: 1em;
  background-color: currentColor;
  margin-left: 2px;
  animation: blink 1s infinite;
}

/* 只有AI消息且内容不完整时才显示光标 */
.ai-message .message-text:not(.message-complete)::after {
  display: inline-block;
}

@keyframes blink {
  0%, 50% {
    opacity: 1;
  }
  51%, 100% {
    opacity: 0;
  }
}

/* 当消息完成时确保隐藏光标 */
.message-complete .message-text::after {
  display: none !important;
}

/* 健康提示卡片 */
.health-tip-card {
  background-color: #fff8e1;
  border-radius: 8px;
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.tip-content {
  flex: 1;
  font-size: 14px;
  color: #ff9800;
}

.tip-arrow {
  color: #ff9800;
  font-size: 20px;
}

/* 每日药物小常识 */
.daily-medicine-tip {
  display: flex;
  align-items: center;
  gap: 5px;
  margin-top: 10px;
}

.tip-icon {
  font-size: 18px;
}

.tip-title {
  font-size: 16px;
  font-weight: bold;
}

.medicine-info {
  background-color: white;
  border-radius: 8px;
  padding: 15px;
  margin-top: 5px;
}

.medicine-title {
  font-weight: bold;
  margin-bottom: 5px;
}

.medicine-content {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}

/* 问题建议区域 */
.question-suggestion {
  margin-top: 10px;
}

.suggestion-title {
  font-size: 16px;
  margin-bottom: 10px;
}

.suggestion-items {
  display: flex;
  flex-direction: column;
  gap: 10px;
  width: 250px;
}

.suggestion-item {
  background-color: white;
  padding: 12px;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.suggestion-item:hover {
  background-color: #f0f0f0;
}

/* 底部功能按钮 */
.bottom-buttons {
  display: flex;
  gap: 15px;
  margin-bottom: 15px;
  width: 250px;
}

.button {
  flex: 1;
  text-align: center;
  background-color: #e3f2fd;
  color: #2196f3;
  padding: 12px;
  border-radius: 20px;
  font-size: 14px;
}

/* 功能菜单遮罩层 */
.menu-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  z-index: 998;
}

/* 功能菜单 */
.function-menu {
  position: fixed;
  bottom: 80px;
  left: 50%;
  transform: translateX(-50%);
  background-color: white;
  border-radius: 12px;
  padding: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  z-index: 999;
  display: flex;
  gap: 8px;
  max-width: 400px;
}

.menu-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12px 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
  min-width: 60px;
}

.menu-item:hover {
  background-color: #f5f5f5;
}

.menu-icon {
  font-size: 24px;
  margin-bottom: 4px;
}

.menu-text {
  font-size: 12px;
  color: #333;
  text-align: center;
}

/* 输入容器样式 */
.input-container {
  position: fixed;
  bottom: 80px;
  left: 0;
  right: 0;
  background-color: white;
  border-top: 1px solid #eee;
  padding: 10px;
  z-index: 100;
  max-width: 500px;
  margin: 0 auto;
}

.input-icon {
  margin-right: 10px;
  font-size: 18px;
  color: #999;
}

.voice-icon {
  cursor: pointer;
  padding: 8px;
  border-radius: 50%;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.voice-icon:hover {
  background-color: #f0f0f0;
}

.voice-icon.recording {
  background-color: #ffebee;
  animation: pulse 1.5s infinite;
}

/* 消息中的图片样式 - 优化版本 */
.message-image {
  margin-bottom: 12px;
  position: relative;
}

.message-image img {
  max-width: 280px;
  max-height: 280px;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  object-fit: cover;
  transition: all 0.3s ease;
  cursor: pointer;
  border: 2px solid rgba(255, 255, 255, 0.8);
}

.message-image img:hover {
  transform: scale(1.02);
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.2);
}

/* 图片加载动画 */
.message-image img {
  opacity: 0;
  animation: fadeInImage 0.5s ease forwards;
}

@keyframes fadeInImage {
  from {
    opacity: 0;
    transform: scale(0.95);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

/* 图片预览容器 - 优化版本 */
.image-preview-container,
.file-preview-container {
  margin-bottom: 12px;
  padding: 12px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 12px;
  border: 1px solid #dee2e6;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 分析提示样式 */
.analysis-tip {
  margin-top: 12px;
  padding: 10px 12px;
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
  border: 1px solid #2196f3;
  border-radius: 8px;
  font-size: 13px;
  color: #1565c0;
  line-height: 1.4;
  box-shadow: 0 2px 4px rgba(33, 150, 243, 0.1);
}

.image-preview,
.file-preview {
  position: relative;
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.preview-image {
  width: 70px;
  height: 70px;
  object-fit: cover;
  border-radius: 8px;
  border: 2px solid #e9ecef;
  transition: all 0.3s ease;
}

.preview-image:hover {
  border-color: #007bff;
  transform: scale(1.05);
}

.image-info,
.file-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.image-name,
.file-name {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 200px;
}

.image-size,
.file-size {
  font-size: 12px;
  color: #6c757d;
  background-color: #f8f9fa;
  padding: 2px 6px;
  border-radius: 4px;
  display: inline-block;
  width: fit-content;
}

.file-type {
  font-size: 11px;
  color: #868e96;
  background-color: #e9ecef;
  padding: 1px 4px;
  border-radius: 3px;
  display: inline-block;
  width: fit-content;
}

.file-icon {
  width: 70px;
  height: 70px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 2px solid #e9ecef;
}

.file-image-preview {
  width: 70px;
  height: 70px;
  border-radius: 8px;
  overflow: hidden;
}

.remove-image-btn,
.remove-file-btn {
  position: absolute;
  top: -8px;
  right: -8px;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
  color: white;
  border: 2px solid white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  line-height: 1;
  box-shadow: 0 2px 8px rgba(220, 53, 69, 0.3);
  transition: all 0.3s ease;
}

.remove-image-btn:hover,
.remove-file-btn:hover {
  background: linear-gradient(135deg, #c82333 0%, #a71e2a 100%);
  transform: scale(1.1);
  box-shadow: 0 4px 12px rgba(220, 53, 69, 0.4);
}

/* 输入行样式 */
.input-row {
  display: flex;
  align-items: center;
  gap: 10px;
}

.question-input {
  flex: 1;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 25px;
  font-size: 16px;
  outline: none;
  background-color: #f8f9fa;
}

.question-input:focus {
  border-color: #007bff;
  background-color: white;
}

.question-input.speech-input {
  border-color: #4CAF50 !important;
  background-color: #f0fff0 !important;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
}

.speech-input::placeholder {
  color: #4CAF50;
  font-style: italic;
}

.send-btn {
  padding: 8px 10px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s;
}

.send-btn:hover:not(:disabled) {
  background-color: #0056b3;
}

.send-btn:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
}

/* 语音设置按钮样式 */
.speech-settings-btn {
  background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
  color: white;
  border: none;
  padding: 8px 12px;
  border-radius: 20px;
  font-size: 16px;
  cursor: pointer;
  margin-right: 10px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.speech-settings-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(76, 175, 80, 0.3);
}

/* 历史记录弹窗样式 - 从左侧滑出 */
.history-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: flex-start;
  justify-content: flex-start;
  animation: fadeIn 0.3s ease-out;
}

.history-modal {
  background: white;
  width: 80%;
  max-width: 400px;
  height: 100%;
  border-radius: 0 15px 15px 0;
  box-shadow: 2px 0 20px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  transform: translateX(-100%);
  animation: slideInFromLeft 0.3s ease-out forwards;
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideInFromLeft {
  from {
    transform: translateX(-100%);
  }
  to {
    transform: translateX(0);
  }
}

@keyframes slideOutToLeft {
  from {
    transform: translateX(0);
  }
  to {
    transform: translateX(-100%);
  }
}

/* 关闭动画 */
.history-modal.closing {
  animation: slideOutToLeft 0.3s ease-out forwards;
}

.history-modal-overlay.closing {
  animation: fadeOut 0.3s ease-out forwards;
}

@keyframes fadeOut {
  from {
    opacity: 1;
  }
  to {
    opacity: 0;
  }
}

/* 历史记录头部 */
.history-header {
  padding: 20px;
  border-bottom: 1px solid #eee;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 0 15px 0 0;
}

.history-header h3 {
  margin: 0 0 15px 0;
  font-size: 18px;
  font-weight: 600;
}

.history-actions {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}

.history-search-input {
  flex: 1;
  min-width: 150px;
  padding: 8px 12px;
  border: none;
  border-radius: 20px;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  placeholder-color: rgba(255, 255, 255, 0.7);
}

.history-search-input::placeholder {
  color: rgba(255, 255, 255, 0.7);
}

.clear-all-btn {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  color: white;
  padding: 8px 12px;
  border-radius: 15px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.clear-all-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

/* 历史记录内容区域 */
.history-content {
  flex: 1;
  overflow-y: auto;
  padding: 0;
}

.no-history {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #999;
}

.no-history-icon {
  font-size: 48px;
  margin-bottom: 10px;
}

.no-history-text {
  font-size: 16px;
}

/* 历史记录列表 */
.history-list {
  padding: 0;
}

.history-item {
  padding: 15px 20px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s;
  position: relative;
}

.history-item:hover {
  background-color: #f8f9fa;
}

.history-item:last-child {
  border-bottom: none;
}

.history-item-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}

.history-type-icon {
  font-size: 16px;
  width: 24px;
  text-align: center;
}

.history-query {
  flex: 1;
  font-weight: 500;
  color: #333;
  font-size: 14px;
  line-height: 1.4;
}

.history-action-hint {
  font-size: 12px;
  color: #999;
  text-align: center;
  margin-top: 8px;
  font-style: italic;
  padding: 4px;
}

.history-item:hover .history-action-hint {
  color: #007bff;
}

.delete-history-btn {
  background: none;
  border: none;
  font-size: 16px;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.delete-history-btn:hover {
  background-color: #f0f0f0;
}

.history-timestamp {
  font-size: 12px;
  color: #999;
  margin-bottom: 8px;
  margin-left: 34px;
}

.history-result-preview {
  font-size: 13px;
  color: #666;
  line-height: 1.4;
  margin-left: 34px;
  background: #f8f9fa;
  padding: 8px 10px;
  border-radius: 6px;
  border-left: 3px solid #e9ecef;
}

/* 语音设置弹窗样式 */
.speech-settings-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.speech-settings-modal {
  background: white;
  border-radius: 20px;
  width: 90%;
  max-width: 400px;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
}

.settings-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.settings-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s ease;
}

.close-btn:hover {
  background: #f5f5f5;
  color: #333;
}

.settings-content {
  padding: 20px;
}

.setting-item {
  margin-bottom: 20px;
}

.setting-item label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

/* 开关样式 */
.switch-label {
  display: flex !important;
  align-items: center;
  cursor: pointer;
  gap: 12px;
}

.switch-label input[type="checkbox"] {
  display: none;
}

.switch-slider {
  position: relative;
  width: 50px;
  height: 24px;
  background: #ccc;
  border-radius: 24px;
  transition: all 0.3s ease;
}

.switch-slider:before {
  content: '';
  position: absolute;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: white;
  top: 2px;
  left: 2px;
  transition: all 0.3s ease;
}

.switch-label input:checked + .switch-slider {
  background: #4CAF50;
}

.switch-label input:checked + .switch-slider:before {
  transform: translateX(26px);
}

.switch-label input:disabled + .switch-slider {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 选择框和滑块样式 */
.voice-select {
  width: 100%;
  padding: 10px;
  border: 2px solid #eee;
  border-radius: 8px;
  font-size: 14px;
  background: white;
  cursor: pointer;
}

.voice-select:focus {
  outline: none;
  border-color: #4CAF50;
}

.range-slider {
  width: 100%;
  height: 6px;
  border-radius: 3px;
  background: #ddd;
  outline: none;
  cursor: pointer;
}

.range-slider::-webkit-slider-thumb {
  appearance: none;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: #4CAF50;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(0,0,0,0.2);
}

.range-slider::-moz-range-thumb {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: #4CAF50;
  cursor: pointer;
  border: none;
  box-shadow: 0 2px 4px rgba(0,0,0,0.2);
}

.test-speech-btn {
  background: linear-gradient(135deg, #9C27B0 0%, #7B1FA2 100%);
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 12px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.test-speech-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(156, 39, 176, 0.3);
}

.settings-footer {
  padding: 20px;
  border-top: 1px solid #eee;
  text-align: center;
}

.confirm-btn {
  background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
  color: white;
  border: none;
  padding: 12px 30px;
  border-radius: 12px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.confirm-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(76, 175, 80, 0.3);
}

/* 消息控制按钮样式 */
.message-controls {
  display: flex;
  gap: 8px;
  margin-top: 8px;
  align-items: center;
}

.speech-btn, .stop-btn {
  background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
  color: white;
  border: none;
  padding: 6px 10px;
  border-radius: 15px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 35px;
  height: 30px;
}

.speech-btn:hover, .stop-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(76, 175, 80, 0.3);
}

.speech-btn.speaking {
  background: linear-gradient(135deg, #FF9800 0%, #F57C00 100%);
  animation: pulse 1.5s infinite;
}

.speech-btn.paused {
  background: linear-gradient(135deg, #2196F3 0%, #1976D2 100%);
}

.stop-btn {
  background: linear-gradient(135deg, #f44336 0%, #d32f2f 100%);
}

/* 语音识别状态样式 */
.speech-status {
  position: fixed;
  top: 70px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1000;
  max-width: 400px;
  width: 90%;
}

.speech-error {
  color: #ff4444;
  font-size: 12px;
  margin-top: 4px;
  padding: 4px 8px;
  background-color: #ffebee;
  border-radius: 4px;
  border-left: 3px solid #ff4444;
}

.speech-preview {
  color: #4CAF50;
  font-size: 12px;
  margin-top: 4px;
  padding: 4px 8px;
  background-color: #e8f5e8;
  border-radius: 4px;
  border-left: 3px solid #4CAF50;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 脉冲动画优化 */
@keyframes pulse {
  0% {
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(220, 53, 69, 0.7);
  }
  70% {
    transform: scale(1.02);
    box-shadow: 0 0 0 10px rgba(220, 53, 69, 0);
  }
  100% {
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(220, 53, 69, 0);
  }
}

/* 语音控制按钮样式 */
.voice-controls {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 10px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.voice-control-btn {
  padding: 8px 12px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 12px;
  font-weight: 500;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 4px;
}

.pause-btn {
  background-color: #ffc107;
  color: #212529;
}

.pause-btn:hover {
  background-color: #e0a800;
}

.resume-btn {
  background-color: #28a745;
  color: white;
}

.resume-btn:hover {
  background-color: #218838;
}

.stop-btn {
  background-color: #dc3545;
  color: white;
}

.stop-btn:hover {
  background-color: #c82333;
}

/* 摄像头界面样式 */
.camera-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.9);
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.camera-container {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  max-width: 90vw;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
}

.camera-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.camera-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.close-camera-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #666;
  padding: 5px;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-camera-btn:hover {
  background-color: #f5f5f5;
}

.camera-preview {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  background-color: #000;
}

.camera-video {
  width: 100%;
  height: auto;
  max-height: 60vh;
  object-fit: cover;
}

.camera-controls {
  display: flex;
  justify-content: center;
  gap: 15px;
}

.take-photo-btn {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 25px;
  font-size: 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: background-color 0.3s ease;
}

.take-photo-btn:hover {
  background-color: #0056b3;
}

.take-photo-btn:active {
  transform: scale(0.98);
}

/* 全屏摄像头界面样式 - 移动端优化 */
.camera-fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #000;
  z-index: 1000;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  /* 移动端安全区域适配 */
  padding-top: env(safe-area-inset-top);
  padding-bottom: env(safe-area-inset-bottom);
  /* 防止页面滚动 */
  touch-action: none;
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  user-select: none;
}

.camera-video-fullscreen {
  width: 100%;
  height: 100%;
  object-fit: contain; /* 从 cover 改为 contain，保持原始比例 */
  background-color: #000;
  /* 移动端优化 */
  -webkit-transform: translateZ(0);
  transform: translateZ(0);
}

.camera-top-bar {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: calc(80px + env(safe-area-inset-top));
  background: linear-gradient(180deg, rgba(0,0,0,0.9) 0%, rgba(0,0,0,0.7) 50%, rgba(0,0,0,0) 100%);
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: calc(20px + env(safe-area-inset-top)) 20px 20px 20px;
  z-index: 1001;
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
}

.close-camera-btn-fullscreen {
  background: rgba(0, 0, 0, 0.6);
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  width: 44px;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  backdrop-filter: blur(15px);
  -webkit-backdrop-filter: blur(15px);
  transition: all 0.3s ease;
  /* 移动端触摸优化 */
  -webkit-tap-highlight-color: transparent;
  touch-action: manipulation;
}

.close-camera-btn-fullscreen:hover,
.close-camera-btn-fullscreen:active {
  background: rgba(0, 0, 0, 0.8);
  border-color: rgba(255, 255, 255, 0.5);
  transform: scale(1.05);
}

.close-icon {
  color: white;
  font-size: 20px;
  font-weight: bold;
  line-height: 1;
}

.recording-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  background: rgba(0, 0, 0, 0.8);
  border: 1px solid rgba(220, 53, 69, 0.5);
  padding: 10px 14px;
  border-radius: 25px;
  backdrop-filter: blur(15px);
  -webkit-backdrop-filter: blur(15px);
}

.recording-dot {
  width: 10px;
  height: 10px;
  background-color: #dc3545;
  border-radius: 50%;
  animation: pulse 1s infinite;
}

.recording-time {
  color: white;
  font-size: 14px;
  font-weight: 600;
  font-family: 'Courier New', monospace;
  letter-spacing: 0.5px;
}

.camera-bottom-bar {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: calc(120px + env(safe-area-inset-bottom));
  background: linear-gradient(0deg, rgba(0,0,0,0.9) 0%, rgba(0,0,0,0.7) 50%, rgba(0,0,0,0) 100%);
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px 20px calc(20px + env(safe-area-inset-bottom)) 20px;
  z-index: 1001;
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
}

.camera-controls-wrapper {
  display: flex;
  gap: 50px;
  align-items: center;
  justify-content: center;
}

.camera-action-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.modern-capture-btn,
.modern-record-btn {
  width: 75px;
  height: 75px;
  border: 3px solid rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.4);
  backdrop-filter: blur(15px);
  -webkit-backdrop-filter: blur(15px);
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  color: white;
  /* 移动端触摸优化 */
  -webkit-tap-highlight-color: transparent;
  touch-action: manipulation;
  /* 防止双击缩放 */
  -webkit-user-select: none;
  user-select: none;
}

.modern-capture-btn:hover:not(:disabled),
.modern-record-btn:hover {
  transform: scale(1.08);
  background: rgba(0, 0, 0, 0.6);
  border-color: #007bff;
  box-shadow: 0 0 25px rgba(0, 123, 255, 0.4), 0 0 50px rgba(0, 123, 255, 0.2);
}

.modern-capture-btn:active:not(:disabled),
.modern-record-btn:active {
  transform: scale(0.95);
  background: rgba(0, 0, 0, 0.7);
}

.modern-capture-btn:disabled {
  opacity: 0.4;
  cursor: not-allowed;
  background: rgba(0, 0, 0, 0.2);
}

.modern-record-btn:hover {
  border-color: #dc3545;
  box-shadow: 0 0 25px rgba(220, 53, 69, 0.4), 0 0 50px rgba(220, 53, 69, 0.2);
}

.modern-record-btn.recording {
  border-color: #dc3545;
  background: rgba(0, 0, 0, 0.6);
  animation: pulse 2s infinite;
  box-shadow: 0 0 20px rgba(220, 53, 69, 0.5);
}

.capture-icon,
.record-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 6px;
  font-size: 24px;
}

.btn-label {
  font-size: 11px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.8px;
  opacity: 0.9;
  text-align: center;
}

.capture-btn {
  width: 70px;
  height: 70px;
  border: 4px solid white;
  border-radius: 50%;
  background: transparent;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
  position: relative;
}

.capture-btn:hover:not(:disabled) {
  transform: scale(1.1);
  border-color: #007bff;
}

.capture-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.capture-btn-inner {
  width: 50px;
  height: 50px;
  background-color: white;
  border-radius: 50%;
  transition: all 0.2s ease;
}

.capture-btn:active:not(:disabled) .capture-btn-inner {
  transform: scale(0.9);
}

.record-btn {
  width: 70px;
  height: 70px;
  border: 4px solid white;
  border-radius: 50%;
  background: transparent;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  position: relative;
}

.record-btn:hover {
  transform: scale(1.1);
  border-color: #dc3545;
}

.record-btn-inner {
  width: 20px;
  height: 20px;
  background-color: #dc3545;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.record-btn.recording {
  border-color: #dc3545;
  animation: pulse 2s infinite;
}

.record-btn.recording .record-btn-inner {
  background-color: #dc3545;
  border-radius: 4px;
  width: 16px;
  height: 16px;
}

.camera-instructions {
  position: absolute;
  bottom: calc(140px + env(safe-area-inset-bottom));
  left: 0;
  right: 0;
  text-align: center;
  z-index: 1001;
  padding: 0 20px;
}

.camera-instructions p {
  color: white;
  font-size: 14px;
  margin: 0;
  padding: 10px 16px;
  background: rgba(0, 0, 0, 0.7);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 25px;
  display: inline-block;
  backdrop-filter: blur(15px);
  -webkit-backdrop-filter: blur(15px);
  max-width: 90%;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .camera-container {
    padding: 15px;
    max-width: 95vw;
  }
  
  .camera-video {
    max-height: 50vh;
  }
  
  .take-photo-btn {
    padding: 10px 20px;
    font-size: 14px;
  }
  
  .camera-top-bar {
    height: calc(70px + env(safe-area-inset-top));
    padding: calc(15px + env(safe-area-inset-top)) 15px 15px 15px;
  }
  
  .close-camera-btn-fullscreen {
    width: 40px;
    height: 40px;
  }
  
  .close-icon {
    font-size: 18px;
  }
  
  .camera-bottom-bar {
    height: calc(100px + env(safe-area-inset-bottom));
    padding: 15px 15px calc(15px + env(safe-area-inset-bottom)) 15px;
  }
  
  .camera-controls-wrapper {
    gap: 40px;
  }
  
  .modern-capture-btn,
  .modern-record-btn {
    width: 70px;
    height: 70px;
    border-width: 2px;
  }
  
  .capture-icon,
  .record-icon {
    font-size: 22px;
    margin-bottom: 4px;
  }
  
  .btn-label {
    font-size: 10px;
    letter-spacing: 0.6px;
  }
  
  .camera-instructions {
    bottom: calc(120px + env(safe-area-inset-bottom));
  }
  
  .camera-instructions p {
    font-size: 13px;
    padding: 8px 14px;
  }
}

/* 超小屏幕优化 */
@media (max-width: 360px) {
  .camera-controls-wrapper {
    gap: 30px;
  }
  
  .modern-capture-btn,
  .modern-record-btn {
    width: 65px;
    height: 65px;
  }
  
  .capture-icon,
  .record-icon {
    font-size: 20px;
  }
  
  .btn-label {
    font-size: 9px;
  }
}

/* 横屏模式优化 */
@media (orientation: landscape) and (max-height: 500px) {
  .camera-top-bar {
    height: calc(60px + env(safe-area-inset-top));
    padding: calc(10px + env(safe-area-inset-top)) 20px 10px 20px;
  }
  
  .camera-bottom-bar {
    height: calc(80px + env(safe-area-inset-bottom));
    padding: 10px 20px calc(10px + env(safe-area-inset-bottom)) 20px;
  }
  
  .camera-controls-wrapper {
    gap: 60px;
  }
  
  .modern-capture-btn,
  .modern-record-btn {
    width: 60px;
    height: 60px;
  }
  
  .camera-instructions {
    bottom: calc(90px + env(safe-area-inset-bottom));
  }
  
  .camera-instructions p {
    font-size: 12px;
    padding: 6px 12px;
  }
}

/* 消息包装器 */
.message-wrapper {
  position: relative;
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

/* 消息操作按钮 */
.message-actions {
  position: relative;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.message:hover .message-actions {
  opacity: 1;
}

.more-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  color: #666;
  font-size: 16px;
  transition: background-color 0.2s ease;
}

.more-btn:hover {
  background-color: #f0f0f0;
  color: #333;
}

/* 操作菜单 */
.message-menu {
  position: absolute;
  top: 100%;
  right: 0;
  background: white;
  border: 1px solid #ddd;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  min-width: 120px;
  overflow: hidden;
}

.menu-item {
  display: block;
  width: 100%;
  padding: 12px 16px;
  border: none;
  background: none;
  text-align: left;
  cursor: pointer;
  font-size: 14px;
  color: #333;
  transition: background-color 0.2s ease;
}

.menu-item:hover {
  background-color: #f5f5f5;
}

.menu-item.delete {
  color: #ff4444;
}

.menu-item.delete:hover {
  background-color: #fff5f5;
}

/* 编辑模式样式 */
.message-edit {
  width: 100%;
}

.edit-textarea {
  width: 100%;
  /* padding: 8px 12px; */
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 14px;
  font-family: inherit;
  resize: vertical;
  min-height: 60px;
  outline: none;
  transition: border-color 0.2s ease;
}

.edit-textarea:focus {
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}

.edit-buttons {
  display: flex;
  gap: 8px;
  margin-top: 8px;
  justify-content: flex-end;
}

.save-btn, .cancel-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: background-color 0.2s ease;
}

.save-btn {
  background-color: #007bff;
  color: white;
}

.save-btn:hover {
  background-color: #0056b3;
}

.cancel-btn {
  background-color: #6c757d;
  color: white;
}

.cancel-btn:hover {
  background-color: #545b62;
}



/* 底部导航栏样式 */
.tabbar-new {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 16px;
  margin: 0 auto;
  width: 92vw;
  max-width: 420px;
  height: 56px;
  background: #fff;
  border-radius: 28px;
  box-shadow: 0 2px 16px 0 rgba(24,119,242,0.08);
  display: flex;
  justify-content: space-around;
  align-items: center;
  z-index: 200;
}

.tabbar-new .tabbar-item {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  height: 100%;
  cursor: pointer;
  transition: color 0.2s;
}

.tabbar-new .tabbar-item.active svg {
  stroke: #1877F2;
}

.icon-wrap {
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.icon-bell-wrap {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-bell-wrap .dot {
  position: absolute;
  top: 2px;
  right: 2px;
  width: 8px;
  height: 8px;
  background: #ff4d4f;
  border-radius: 50%;
  border: 2px solid #fff;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .speech-settings-modal {
    width: 95%;
    margin: 20px;
  }
  

  
  .message-controls {
    flex-wrap: wrap;
  }
  
  .speech-btn, .stop-btn {
    font-size: 12px;
    padding: 4px 8px;
    min-width: 30px;
    height: 26px;
  }
  
  .message-menu {
    right: -10px;
    min-width: 100px;
  }
  
  .menu-item {
    padding: 10px 12px;
    font-size: 13px;
  }
  
  .edit-textarea {
    min-height: 50px;
    font-size: 13px;
  }
  
  .save-btn, .cancel-btn {
    padding: 5px 10px;
    font-size: 11px;
  }
  
  /* 历史记录响应式设计 */
  .history-modal {
    width: 90%;
  }
  
  .history-actions {
    flex-direction: column;
    align-items: stretch;
  }
  
  .history-search-input {
    min-width: auto;
  }
}
</style>
